package nl.borchef.map_2d_game;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;

class game_thread extends Thread {
	private SurfaceHolder mo_surface_holder;
	private game mo_game;
    private Handler mo_handler;
    private long ml_start_time = 0;
    private long ml_fps = 25;
	private long ml_frame_time = 1000 / ml_fps;
    // constructor
	public game_thread(SurfaceHolder surfaceHolder, Context context,
			Handler handler, game game) {
        //Log.d(this.getClass().getName(), "class created");
		mo_surface_holder = surfaceHolder;
		mo_handler = handler;
		mo_game = game;
	}

	public void pause(boolean paused) {
        //Log.d(this.getClass().getName(), "pause");
        mo_game.set_paused(paused);
	}
	
	public void save_stop() {
        //Log.d(this.getClass().getName(), "save_stop");
        mo_game.set_running(false);
	}
	
	void surface_ready( boolean ready ){
		mo_game.set_surface_ready(ready);
	}

    @Override
	public synchronized void start() {
		mo_game.set_running(true);
		super.start();
	}

	@Override
    public void run() {
        //Log.d(this.getClass().getName(), "run");
    	while( mo_game.get_running() )
    	{
    		//Log.d(this.getClass().getName(), "run running");
    		long start_time = System.currentTimeMillis();
            Canvas canvas = null;
            try {
            	if( !mo_game.get_paused() && mo_game.get_surface_ready() ){
        			mo_game.update();
            	}
            	if( mo_game.get_surface_ready() ){
                    canvas = mo_surface_holder.lockCanvas();
                    if( canvas != null ){
                    	mo_game.draw(canvas);
                    }
            	}
        		if( mo_game.get_paused() || !mo_game.get_surface_ready() ){
            		sleep(10);
            	}
			} 
            catch (InterruptedException e) {
			}
            finally{
                if( canvas != null ){
                	mo_surface_holder.unlockCanvasAndPost(canvas);
                }
        		long end_time = System.currentTimeMillis();
            	if( !mo_game.get_paused() && mo_game.get_surface_ready() ){
            		long work_time = end_time - start_time;
            		if( work_time < ml_frame_time ){
            			try {
							sleep(ml_frame_time-work_time);
						} catch (InterruptedException e) {

						}
            		}
            	}
            }
    	}
    }

	public void set_surface_size(int width, int height) {
		mo_game.set_canvas_width(width);
		mo_game.set_canvas_height(height);
	}
}

